import os
exchange = {'H': 'e', 'r': 'h', 'Z': 't',
            't': 'p', 'v': '1', '4': '2',
            'n': '3', 'x': '4', 'f': '5',
            'k': '6', 'i': '7', 'A': '8',
            'O': '9', 'b': '0', 'y': 'o',
            '1': 'r', 'C': 'm', 'q': 'u',
            'V': 'n', 'm': 'f', 'D': 'I',
            'N': 's', '6': 'i', 'K': 'a',
            '9': 'd', 'u': 'g', 'a': 'W',
            'R': 'l', 'Q': 'c', 'J': 'y',
            'U': 'E', 'F': 'x', 'l': 'b',
            'Y': 'B', 'h': 'w', '2': 'T',
            'E': 'R', 'c': 'S', 'P': 'k',
            'z': 'H', '8': 'C', 'B': 'J',
            'p': 'D', '7': 'M', '3': 'U',
            'I': 'v', 'g': 'L', 'W': 'A',
            '5': 'O', 'X': 'K', 'M': 'P',
            'j': 'z', 'd': 'Y', 'o': 'F',
            'T': 'V', 'e': 'N', 's': 'G',
            'G': 'Q', '0': 'j', 'w': 'q',
            'L': 'Z', 'S': 'X'
            }
def processLine(line, CharacterCounts):
    for character in line:
        #if character.isalpha() or character.isdigit():
            #CharacterCounts[character] += 1
        if ord(character) in range(48, 58) or ord(character) in range(65, 91) or ord(character) in range(97, 123):
            CharacterCounts[character] += 1
        '''if ord(character) in range(65, 91):
            CharacterCounts[character] += 1
        if ord(character) in range(97, 123):
            CharacterCounts[character] += 1'''

def exchangeLine(line):
    line1=''
    for character in line:
        if ord(character) in range(48, 58) or ord(character) in range(65, 91) or ord(character) in range(97, 123):
            character=exchange[character]
        line1+=character
    return line1

# 创建字母字典
def createCharacterCounts(CharacterCounts):
    for i in range(48, 58):
        CharacterCounts[chr(i)] = 0
    for i in range(65, 91):
        CharacterCounts[chr(i)] = 0
    for i in range(97, 123):
        CharacterCounts[chr(i)] = 0


def main(path):
    #path = '../英文小说'  # 待读取文件的文件夹绝对地址

    #print(files)
    # 建立用于计算词频的空字典
    CharacterCounts = {}
    # 初始化字典键值
    createCharacterCounts(CharacterCounts)
    if not os.path.isdir(path):  # 判断是否是文件夹
        infile = open(path, "r", encoding="ISO-8859-1")
        for line in infile:
            processLine(line, CharacterCounts)
        infile.close()

    else:
        files = os.listdir(path)  # 获得文件夹中所有文件的名称列表
        for file in files:
            #f = open(path + "/" + file)

            infile = open(path + "/" + file, "r",encoding="ISO-8859-1")
            for line in infile:
                processLine(line, CharacterCounts)
            infile.close()

        '''if not os.path.isdir(file):  # 判断是否是文件夹
            f = open(path + "/" + file)
            s = []  # 初始化列表
            print(s.append(f))
        else:
            path1 = path + "/" + file
            files1 = os.listdir(path1)
            for file1 in files1:
                f = open(path1 + "/" + file1)
                s = []  # 初始化列表
                for ii in f:  # 遍历文件，一行行读取，并添加到s中
                    s.append(ii)
                    list1.append(s)'''
    # 从字典中获取数据对
    pairs = list(CharacterCounts.items())

    # 列表中的数据对交换位置,数据对排序
    items = [[x, y] for (y, x) in pairs]
    items.sort(reverse=True)

    #print(path)
    # 输出count个数词频结果
    text = ''
    for i in range(len(items)):
        #print(items[i][1] + "\t" + str(items[i][0]))
        text+=items[i][1] + "\t" + str(items[i][0])+ "\n"
    #print(text)
    #infile.close()
    return text
def change(path):
    text = ''
    outfile = open("../secretDecrypt.txt", "w")
    if not os.path.isdir(path):  # 判断是否是文件夹
        infile = open(path, "r", encoding="ISO-8859-1")
        for line in infile:
            line1=exchangeLine(line)
            outfile.write(line1)
            #print(line1)
            text+=line1
        infile.close()
    #print(text)
    #outfile=open("../secretDecrypt.txt", "w")
    outfile.close()
    return text

def frequency():
    path = '../英文小说'
    text1=main(path)
    path1 = './secret.txt'
    text2 =main(path1)
    return text1,text2
def show():
    text1="代换表：\n"
    text1+="H -> e r -> h Z -> t\n"+"t -> p v -> 1（数字1） 4 -> 2\n"+"n -> 3 x -> 4 f -> 5\n"+"k -> 6 i -> 7 A -> 8\n"+"O -> 9 b -> 0 y -> o\n"+"1 - > r C -> m q -> u\n"+"V -> n m -> f D -> I（大写i）\n"+"N -> s 6 -> i K -> a\n"+"9 -> d u -> g a -> W\n"+"R -> l（小写L） Q -> c J -> y\n"+"U -> E F -> x l(小写L) -> b\n"+"Y -> B h -> w 2 -> T\n"+"E -> R c -> S P -> k\n"+"z -> H 8 -> C B -> J\n"+"p -> D 7 -> M 3 -> U\n"+"I(大写i) -> v g -> L W -> A\n"+"5 -> O X -> K M -> P\n"+"j -> z d ->Y  o -> F\n"+"T -> V e -> N s -> G\n"+"G -> Q 0 -> j w -> q\n"+"L -> Z S -> X"
    path1 = './secret.txt'
    text2=change(path1)
    return text1,text2

# 调用main()函数
if __name__ == '__main__':
    '''path = '../英文小说'
    main(path)
    path1 = '../secret.txt'
    main(path1)'''
    #path1 = '../secret.txt'
    #change(path1)
    path = '../英文小说'
    text1 = main(path)
    path1 = '../secret.txt'
    text2 = main(path1)
    #return text1, text2

'''
H -> e r -> h Z -> t
t -> p v -> 1（数字1） 4 -> 2
n -> 3 x -> 4 f -> 5
k -> 6 i -> 7 A -> 8
O -> 9 b -> 0 y -> o
1 - > r C -> m q -> u
V -> n m -> f D -> I（大写i）
N -> s 6 -> i K -> a
9 -> d u -> g a -> W
R -> l（小写L） Q -> c J -> y
U -> E F -> x l(小写L) -> b
Y -> B h -> w 2 -> T
E -> R c -> S P -> k
z -> H 8 -> C B -> J
p -> D 7 -> M 3 -> U
I(大写i) -> v     g -> L      W -> A
5 -> O     X -> K      M -> P
j -> z       d ->Y        o -> F
T -> V     e -> N      s -> G
G -> Q    0 -> j w -> q
L -> Z S -> X
'''